from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from tkinter import font as tkfont
from threading import Thread
from mini_tools.cjjtool import *
from mini_tools.myexcel import *
from mini_tools.mytools import *
from mini_tools.uitool import *
from sql import sqlseverDB
from config import *
import tkinter.messagebox as messagebox
import time

class ShopeeQKCJ1(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        Label(self, text='虾皮任务(采集)', fg="black", bg="yellow",font=("微软雅黑", 13)).pack(fill=X,padx=2)
        MianBanFrame(self,'虾皮任务(采集)').pack(fill=X,padx=2,pady=2)
class TaskFrame(Frame):
    def __init__(self,master,taskinfo):
        Frame.__init__(self,master)
        table_name_dict={'虾皮':'HouTai','波兰':'HouTai_ALG','菲律宾虾皮':'ShopeePHAccount','泰国虾皮':'HouTai_TH','阿里巴巴':'S1688Account'}
        self.task_id=taskinfo['id']
        self.task_name=taskinfo['tName']
        self.table_name=table_name_dict[taskinfo['pt']]
        self.iszd=taskinfo['iszd']
        self.isMulti=taskinfo['isMulti']
        self.timing=taskinfo['timing']
        self.position=taskinfo['position']
        self.mutilTiming=taskinfo['mutilTiming']

        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.countStr=StringVar()
        self.statusStr=StringVar()
        self.startStr=StringVar()
        self.endStr=StringVar()
        self.countStr.set(f'...')
        self.statusStr.set(f'正在获取任务状态')
        self.startStr.set(f'正在获取上次开始时间')
        self.endStr.set(f'正在获取上次结束时间')
        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):
        label_font = tkfont.Font(family="微软雅黑", size=10, weight="bold")
        f1=Frame(self)
        f1.pack(fill=X,padx=2)

        f00=Frame(f1)
        f00.pack(fill=X,padx=2)
        Label(f00, text=f'《{self.task_name}》',fg='#6B238E',font=("微软雅黑", 12),anchor="w").pack(side=LEFT, padx=2)

        Label(f00, textvariable=self.countStr,fg='red').pack(side=LEFT, padx=2)

        f01=Frame(f1)
        f01.pack(fill=X,padx=2)
        Label(f01, textvariable=self.startStr,fg='#97694F').pack(side=LEFT, padx=2)

        f02=Frame(f1)
        f02.pack(fill=X,padx=2)
        Label(f02, textvariable=self.endStr,fg='#97694F').pack(side=LEFT, padx=2)

        f03=Frame(f1)
        f03.pack(fill=X,padx=2)
        Label(f03, textvariable=self.statusStr,fg='red',width=30,anchor="w").pack(side=LEFT, padx=2)

        f04=Frame(f1)
        f04.pack(fill=X,padx=2)

        if self.isMulti==-1:
            Label(f04, text='《单进程》',font=label_font,fg='#871F78').pack(side=LEFT, padx=2)
        else:
            jc_index_dict={0:0,2:1,3:2,4:3,5:4,6:5,7:6,8:7}
            Label(f04, text='进程:',font=label_font).pack(side=LEFT)
            self.MutilSelect = ttk.Combobox(f04,state="readonly",width=3)
            self.MutilSelect['value']=['单进程','2','3','4','5','6','7','8','12']
            self.MutilSelect.current(jc_index_dict.get(self.isMulti))
            self.MutilSelect.bind("<<ComboboxSelected>>",lambda e :Thread(target=self.on_select_jcnum).start())
            self.MutilSelect.pack(side=LEFT)
        
        # Label(f04, text='定时:',font=label_font).pack(side=LEFT, padx=2)
        # self.TimingSelect = ttk.Combobox(f04,state="readonly",width=6)
        # self.TimingSelect['value']=['无定时']+[str(j) for j in range(0,24)]
        # if self.timing==-1:
        #     self.TimingSelect.current(0)
        # else:
        #     self.TimingSelect.current(self.timing+1)
        # self.TimingSelect.bind("<<ComboboxSelected>>",lambda e :Thread(target=self.on_select_timing).start())
        #self.TimingSelect.pack(side=LEFT, padx=2)

        # f05=Frame(f1)
        # f05.pack(fill=X,padx=2,pady=2)
        Label(f04, text='多定时:',font=label_font).pack(side=LEFT, padx=2)
        self.IptMutilTiming = Entry(f04,width=10)
        self.IptMutilTiming.pack(side=LEFT, padx=2, pady=2)
        if self.mutilTiming:
            self.IptMutilTiming.insert(0,self.mutilTiming)
        
        elif self.timing and self.timing!=-1 and (not self.mutilTiming):
            self.IptMutilTiming.insert(0,self.timing)

        self.btn_set_mutil_timing=Button(f04,text='保存',command=lambda:Thread(target=self.set_mutil_timing).start(),fg='#ffffff',bg='green')
        self.btn_set_mutil_timing.pack(side=LEFT,padx=2)

        f06=Frame(f1)
        f06.pack(fill=X,padx=2,pady=2)
        self.btn_start=Button(f06,text='全部运行',state=DISABLED,command=lambda:Thread(target=self.start_task).start(),fg='#ffffff',bg='green')
        self.btn_start.pack(side=LEFT,padx=2)

        self.btn_continue=Button(f06,text='继续运行',state=DISABLED,command=lambda:Thread(target=self.continue_task).start(),fg='#ffffff',bg='green')
        self.btn_continue.pack(side=LEFT,padx=2)

        self.btn_stop=Button(f06,text='停止运行',command=lambda:Thread(target=self.stop_task).start(),fg='#ffffff',bg='green')
        self.btn_stop.pack(side=LEFT,padx=2)

        self.btn_dc_log=Button(f06,text='导出日志',command=lambda:Thread(target=self.dc_log).start(),fg='#ffffff',bg='green')
        self.btn_dc_log.pack(side=LEFT,padx=2)
    
    def getcount(self):
        while True:
            try:



                if self.task_id==17:
                    rs_search=self.ms.ExecQuery('''select count(*) from S1688Pro p
                        where is_yntit=0 
                        and is_cj=1 
                        and is_yn_ad=0 
                        and pname not like '%定制%'
                        AND NOT EXISTS (
                            SELECT 1
                            FROM Blacklist b
                            WHERE b.word_language = '中文'
                            AND p.pname LIKE '%' + b.word_blacklist + '%')
                    ''')
                    self.countStr.set(f'{rs_search[0][0]} 个')
                elif self.task_id==18:
                    rs_search=self.ms.ExecQuery("select count(*) from S1688Pro where is_yntit=1 and is_fy_sku=0")
                    self.countStr.set(f'{rs_search[0][0]} 个')

                elif self.task_id==19:
                    rs_search=self.ms.ExecQuery("select count(*) from S1688Pro where is_mltit=1 and is_fy_ensku=0")
                    self.countStr.set(f'{rs_search[0][0]} 个')
                elif self.task_id==20:
                    rs_search=self.ms.ExecQuery('''select count(*) from S1688Pro p
                        where is_thtit=0 
                        and is_cj=1 
                        and pname not like '%定制%'
                        AND NOT EXISTS (
                            SELECT 1
                            FROM Blacklist b
                            WHERE b.word_language = '中文'
                            AND p.pname LIKE '%' + b.word_blacklist + '%')
                    ''')
                    self.countStr.set(f'{rs_search[0][0]} 个')
                elif self.task_id==38:
                    rs_search=self.ms.ExecQuery('''select count(*) from S1688Pro p
                        where is_mltit=0 
                        and is_cj=1 
                        and pname not like '%定制%'
                        AND NOT EXISTS (
                            SELECT 1
                            FROM Blacklist b
                            WHERE b.word_language = '中文'
                            AND p.pname LIKE '%' + b.word_blacklist + '%')
                    ''')
                    self.countStr.set(f'{rs_search[0][0]} 个')

                else:
                    if self.iszd:
                        if self.iszd.lower().startswith('select'):
                            sqlstr1=self.iszd
                        else:
                            sqlstr1=f'select count(*) from {self.table_name} where {self.iszd}=1 and is_task_baned=0'
                        rs1=self.ms.ExecQuery(sqlstr1)
                        self.countStr.set(f'{rs1[0][0]} 个')
                    else:
                        self.countStr.set(f'0 个')
                    
                sqlstr2='select [state],[tcount],[LastRunTime],[LastEndTime],[LastHouTaiID] from task where [id]=?'
                rs2=self.ms.ExecQuery(sqlstr2,(self.task_id,))
                rwstatus,rwcount,start_time,end_time,last_hid=rs2[0]
                if rwstatus==0:
                    self.statusStr.set(f'任务未开启,最后运行店铺ID:{last_hid}')
                    self.btn_start.config(state=NORMAL)
                    self.btn_continue.config(state=NORMAL)
                else:
                    self.statusStr.set(f'任务进行中,队列数剩余:{rwcount}')
                    self.btn_start.config(state=DISABLED)
                    self.btn_continue.config(state=DISABLED)

                self.startStr.set(f'上次开始时间:{str(start_time)[:-7]}')
                self.endStr.set(f'上次结束时间:{str(end_time)[:-7]}')

            except Exception as e:
                pass
            time.sleep(20)
    
    def on_select_jcnum(self):

        if self.MutilSelect.current()==0:
            select_jc_num=0
        else:
            select_jc_num=int(self.MutilSelect.get())
        
        print(f'设置任务:《{self.task_name}》至进程数:{select_jc_num}...')

        aff=self.ms.ExecNoQuery('update task set isMulti=? where id=?',(select_jc_num,self.task_id))
        if aff>0:
            get_qukong_data()
            print(f'设置任务:《{self.task_name}》至进程数:{select_jc_num},设置成功')
        else:
            print(f'设置任务:《{self.task_name}》至进程数:{select_jc_num},设置失败')
            
    def on_select_timing(self):

        if self.TimingSelect.current()==0:
            timing_num=-1
        else:
            timing_num=int(self.TimingSelect.get())
        
        print(f'设置任务:《{self.task_name}》定时时间:{timing_num} 点运行...')

        aff=self.ms.ExecNoQuery('update task set timing=? where id=?',(timing_num,self.task_id))
        if aff>0:
            get_qukong_data()
            print(f'设置任务:《{self.task_name}》定时时间:{timing_num} 点运行,设置成功')
        else:
            print(f'设置任务:《{self.task_name}》定时时间:{timing_num} 点运行,设置失败')

    def set_mutil_timing(self):

        pattern = r"^([0-9]|1[0-9]|2[0-3])(\|([0-9]|1[0-9]|2[0-3]))*$"
        mutil_timging_str=self.IptMutilTiming.get().strip()
        
        if not mutil_timging_str:
            mutil_timging_str=None
            if self.timing:
                self.IptMutilTiming.insert(0,self.timing)

            
        else:
            if not re.match(pattern, mutil_timging_str):
                messagebox.showinfo('错误','请输入正确定时格式:2|4|23')
                return

        self.btn_set_mutil_timing.config(state=DISABLED)
        if mutil_timging_str:
            timing=int(mutil_timging_str.split('|')[0])
        else:
            timing=-1
        print(f'设置任务:《{self.task_name}》多个定时时间:{mutil_timging_str} ...')
        
        aff=self.ms.ExecNoQuery('update task set mutilTiming=?,timing=? where id=?',(mutil_timging_str,timing,self.task_id))
        
        if aff>0:
            get_qukong_data()
            print(f'设置任务:《{self.task_name}》多个定时时间:{mutil_timging_str} ,设置成功')
        else:
            print(f'设置任务:《{self.task_name}》多个定时时间:{mutil_timging_str} ,设置失败')
        
        self.btn_set_mutil_timing.config(state=NORMAL)

    def start_task(self):

        if not messagebox.askyesno('提示',f'确定开启{self.task_name}任务?'):
            return
        self.btn_continue.config(state=DISABLED)
        self.btn_start.config(state=DISABLED)
        

        if self.task_id==17:
            sqlstr1="select count(*) from S1688Pro where is_yntit=0 and is_cj=1 and is_yn_ad=0 and pname not like '%定制%'"
        elif self.task_id==18:
            sqlstr1='select count(*) from S1688Pro where is_yntit=1 and is_fy_sku=0'
        
        elif self.task_id==19:
            sqlstr1="select count(*) from S1688Pro where is_mltit=1 and is_fy_ensku=0"

        elif self.task_id==20:
            sqlstr1="select count(*) from S1688Pro where is_thtit=0 and is_cj=1 and pname not like '%定制%'"
        elif self.task_id==38:
            sqlstr1="select count(*) from S1688Pro where is_mltit=0 and is_cj=1 and pname not like '%定制%'"
        
        else:
            sqlstr1=f'select count(*) from {self.table_name} where {self.iszd}=1 and is_task_baned=0'
        if not self.iszd:
            sqlstr1=None
        if sqlstr1:
            rs1=self.ms.ExecQuery(sqlstr1)
            dpcount=rs1[0][0]
        else:
            dpcount=0
        
        self.statusStr.set(f'任务进行中,队列数剩余:{dpcount}')
        aff1=self.ms.ExecNoQuery('update [task] set state=1,tcount=?,LastHouTaiID=null where [id]=?',(dpcount,self.task_id))
        if aff1:
            print(f'开启任务{self.task_name}任务成功')
        else:
            print(f'开启{self.task_name}任务失败')
            messagebox.showerror('提示',f'开启{self.task_name}任务失败')
    
    def continue_task(self):

        if not messagebox.askyesno('提示',f'确定继续{self.task_name}任务?'):
            return
        
        self.btn_continue.config(state=DISABLED)
        self.btn_start.config(state=DISABLED)
        if self.iszd.lower().startswith('select'):
            sqlstr1=self.iszd
        else:
            sql_last='update [task] set LastHouTaiID=999 from [task] where id=?'
            self.ms.ExecNoQuery(sql_last,(self.task_id,))
            
            sqlstr1=f'''select count(*) from taskStatus where task_id={self.task_id} and state=0  
                        and bid in (select browserid from {self.table_name} where {self.iszd}=1 and is_task_baned=0) 
                    '''
        rs1=self.ms.ExecQuery(sqlstr1)
        dpcount=rs1[0][0]
        self.statusStr.set(f'任务进行中,队列数剩余:{dpcount}')
        aff1=self.ms.ExecNoQuery('update [task] set state=1,tcount=? where [id]=?',(dpcount,self.task_id))
        if aff1:
            print(f'继续{self.task_name}任务成功')
        else:
            print(f'继续{self.task_name}任务失败')
            messagebox.showerror('提示',f'继续{self.task_name}任务失败')

    def stop_task(self):

        self.btn_stop.config(state=DISABLED)

        aff=ms.ExecNoQuery('update task set state=-1 where id=? and state!=0',(self.task_id,))
        if aff>0:
            print(f'成功关闭任务《{self.task_name}》')
            messagebox.showinfo('提示',f'成功关闭任务《{self.task_name}》')
        else:
            print(f'关闭任务《{self.task_name}》失败')
            messagebox.showinfo('提示',f'关闭任务《{self.task_name}》失败')

        self.btn_stop.config(state=NORMAL)

    def dc_log(self):

        self.btn_dc_log.config(state=DISABLED)
        rs=self.ms.ExecQuery('select logPath from task where id=?',(self.task_id,))
        if not rs[0][0]:
            print(f'当前没有 {self.task_name} 的运行日志')
        else:
            logPath=rs[0][0]
            url=logPath.replace('D:/Web/Gtupdate',f'http://{UPDATE_URL}')
            print(url)
            while True:
                try:
                    res=requests.get(url)
                    bdpath=logPath.replace('D:/Web/Gtupdate/GTLOG/','')
                    with open(bdpath,'wb') as f:
                        f.write(res.content)
                    print(f'成功导出{self.task_name} 运行日志:《{bdpath}》')
                    messagebox.showinfo('提示',f'成功导出{self.task_name} 运行日志:《{bdpath}》')
                    break 
               
                except Exception as e:
                    print(e)
                    time.sleep(1)
    
        self.btn_dc_log.config(state=NORMAL)

class MianBanFrame(Frame):
    def __init__(self,master,mbName):
        Frame.__init__(self,master)
        self.mbName=mbName
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)

        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):

        if not get_config('QKTask'):
            print('正在加载群控面板数据...')
            get_qukong_data()
        
        rw_datas=get_config('QKTask').get(self.mbName)
        if rw_datas:
            rw_datas.sort(key=lambda item: (item['timing'] == -1, item['timing']))
            row=1;col=1
            for j in range(len(rw_datas)):

                f0= Frame(self)
                f0.grid(row=row, column=col, padx=2,pady=2, sticky="W")
                rw=rw_datas[j]
                TaskFrame(f0,rw).pack(fill=X)
                col+=1
                if col>3:
                    col=col%3
                    row+=1

    
    def getcount(self):
        while True:
            try:
                get_qukong_data()
            except Exception as e:
                pass
            time.sleep(1200)

class ADKWFrame(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.taskid=5
        self.strVars=[StringVar() for j in range(6)]
        [self.strVars[j].set('正在获取状态') for j in range(6)]
        self.btnztStrs=[StringVar() for j in range(6)]
        [self.btnztStrs[j].set('正在获取状态') for j in range(6)]
        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):
        ttk.Separator(self,orient='horizontal').pack(fill=X,pady=2)
        f0=Frame(self)
        f0.pack(fill=X,padx=2,pady=2)
        Label(f0, text='广告标题关键词', fg="white", bg="#007FFF",font=("微软雅黑", 13)).pack(fill=X,padx=5)
        f1=Frame(self)
        f1.pack(fill=X,padx=2,pady=2)

        cits=['一词','二词','三词','四词','五词','六词']
        f01=Frame(f1)
        f01.pack(fill=X,padx=2,pady=2)
        for j in range(3):
            Label(f01, text=f'{cits[j]}:', font=("微软雅黑", 12,"bold")).pack(side=LEFT,padx=2,pady=2)
            Label(f01, textvariable=self.strVars[j],fg='red',width=25,anchor="w").pack(side=LEFT,padx=2, pady=2,fill=X)
        f02=Frame(f1)
        f02.pack(fill=X,padx=2,pady=2)
        for j in range(3,6):
            Label(f02, text=f'{cits[j]}:',  font=("微软雅黑", 12,"bold")).pack(side=LEFT,padx=2,pady=2)
            Label(f02, textvariable=self.strVars[j],fg='red',width=25,anchor="w").pack(side=LEFT,padx=2, pady=2,fill=X)

        
        f03=Frame(f1)
        f03.pack(fill=X,padx=2,pady=2)
        for j in range(3):

            btn_name=f'btn{j}'
            setattr(self, btn_name, Button(f03,text=f'{cits[j]}采集',state=DISABLED,command=lambda j=j:Thread(target=self.start_task,args=(j,)).start(),fg='#ffffff',bg='green'))
            getattr(self, btn_name).pack(side=LEFT,padx=2, pady=2)
            Label(f03, textvariable=self.btnztStrs[j],fg='red',width=20,anchor="w").pack(side=LEFT,padx=2, pady=2,fill=X)
        f04=Frame(f1)
        f04.pack(fill=X,padx=2,pady=2)
        for j in range(3,6):
            btn_name=f'btn{j}'
            setattr(self, btn_name, Button(f04,text=f'{cits[j]}采集',state=DISABLED,command=lambda j=j:Thread(target=self.start_task,args=(j,)).start(),fg='#ffffff',bg='green'))
            getattr(self, btn_name).pack(side=LEFT,padx=2, pady=2)            
            Label(f04, textvariable=self.btnztStrs[j],fg='red',width=20,anchor="w").pack(side=LEFT,padx=2, pady=2,fill=X)

        self.btn_add_onekw=Button(f04,text=f'增加一词',command=lambda:Thread(target=self.add_onekw).start(),fg='#ffffff',bg='green')
        self.btn_add_onekw.pack(side=LEFT,padx=2, pady=2)   

    def getcount(self):
        cits=['一词','二词','三词','四词','五词','六词']
        while True:
            try:
                sqlstr1='''select wordnum,count(case when state=1 then 1 end) as 
                            cjcount,count(case when state=0 then 1 end) as nocjcount from adkeyword where wordnum<=6
                            group by wordnum  order by wordnum'''
                
                rs=self.ms.ExecQuery(sqlstr1)
                wordnums=[r[0] for r in rs]
                for j in range(6):
                    cwnum=j+1
                    if cwnum in wordnums:
                        ycj=rs[j][1]
                        wcj=rs[j][2]
                        self.strVars[j].set(f'已采集:{ycj},未采集:{wcj}')
                    else:
                        self.strVars[j].set(f'已采集:0,未采集:0')
                
                sqlstr2='select id,state,tcount from task where id between 7 and 12'
                rs2=ms.ExecQuery(sqlstr2)
                for tid,state,tcont in rs2:
                    cindex=tid-7
                    if state==0:
                        self.btnztStrs[cindex].set(f'{cits[cindex]}任务未开启')
                        getattr(self, f'btn{cindex}').config(state=NORMAL)
                    else:
                        self.btnztStrs[cindex].set(f'{cits[cindex]}任务队列剩余:{tcont}')
                        getattr(self, f'btn{cindex}').config(state=DISABLED)

            except:
                pass
            time.sleep(10)
    
    def start_task(self,tt):

        if not messagebox.askyesno('提示',f'确定开启{tt+1}词采集?'):
            return
        
        getattr(self, f'btn{tt}').config(state=DISABLED)
        sqlstr1='select count(*) from adkeyword where state=0 and wordnum=?'
        rs1=self.ms.ExecQuery(sqlstr1,(tt+1))
        if rs1[0][0]==0:
            print(f'当前数据库没有{tt+1}词待采集')
            messagebox.showinfo('提示',f'当前数据库没有{tt+1}词待采集')
            getattr(self, f'btn{tt}').config(state=NORMAL)
            return
        

        taskid=tt+7   
        aff1=self.ms.ExecNoQuery('update [task] set state=1,tcount=? where [id]=?',(rs1[0][0],taskid))
        if aff1:
            print(f'开启任务成功,开始采集 {rs1[0][0]} 个{tt+1}词待采集')

        else:
            print('开启任务失败')
            messagebox.showerror('提示','开启任务失败')
            getattr(self, f'btn{tt}').config(state=NORMAL)
        
    def add_onekw(self):
        
        if not messagebox.askyesno('提示','是否一键从表《YN_AD_ID》增加一词数量'):
            return
        
        self.btn_add_onekw.config(state=DISABLED)
        sqlstr='select ad_name from YN_AD_ID where status=? group by Ad_Name'
        rs_tits=ms.ExecQuery(sqlstr,('Ongoing',))
        rs_old_kw=ms.ExecQuery('select kw from ADKeyWord where WordNum=1')
        old_kws=[r[0].lower()  for r in rs_old_kw]
        print(f'当前表《YN_AD_ID》共{len(rs_tits)}个标题,原一词共{len(rs_old_kw)}个')

        new_kws=[]
        for r in rs_tits:
            cur_ad_name=r[0]
            for s in cur_ad_name.split():
                # 匹配只包含字母、数字和连字符，且不能是纯数字，并且字符串长度大于等于 2
                if re.fullmatch(r'[A-Za-z0-9\-]+', s) and not s.isdigit() and len(s) >= 2:
                    if (s not in new_kws) and (s.lower() not in old_kws):
                        new_kws.append(s)
            
        print(f'分割、过滤、去重后共获得:{len(new_kws)} 个一词')
        
        print(f'开始导入到《adkeywords》表...')
        task_count=len(new_kws)
        for kw in new_kws:
            rs=self.ms.ExecQuery('select count(*) from ADKeyWord where kw=?',(kw,))
            if rs[0][0]>0:
                print(f'《{kw}》,导入状态:已存在,剩余:{task_count}')
            else:
                aff=self.ms.ExecNoQuery(f'insert into ADKeyWord(kw,WordNum) values(?,?)',(kw,1))
                print(f'《{kw}》,导入状态:{aff},剩余:{task_count}')
            task_count-=1
        
        print(f'上传一词完毕')
        messagebox.showinfo('提示','上传一词完毕')

        self.btn_add_onekw.config(state=NORMAL)

class GlobalCZ(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.createWidgets()

    def createWidgets(self):
        f1=Frame(self)
        f1.pack(fill=X,padx=2,pady=2)
        DownLog(f1).pack(side=LEFT,fill=Y)
        CloseTask(f1).pack(side=RIGHT,fill=Y)

class DownLog(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.bmCount=IntVar()
        self.rbmCount=IntVar()
        self.createWidgets()

    def createWidgets(self):
        self.rwys={v:k for k,v in TASK_DICT.items()}

        f0=Frame(self)
        f0.pack(fill=X)
        f00=Frame(f0)
        f00.pack(fill=X)

        Label(f00, text='选择任务:').pack(side=LEFT, padx=4, pady=2)
        self.dbnameSelect = ttk.Combobox(f00,state='readonly',width=20)
        self.dbnameSelect['value'] = list(self.rwys.values())
        self.dbnameSelect.pack(side=LEFT, padx=5, pady=2)
        self.dbnameSelect.current(0)
    
        self.dcbtn=Button(f00,text='导出运行日志',command=lambda:Thread(target=self.start_dc).start(),fg='#ffffff',bg='green')
        self.dcbtn.pack(side=LEFT, padx=2, pady=2)
    
    def start_dc(self):

        self.dcbtn.config(state=DISABLED)
        cur_taskid=list(self.rwys.keys())[self.dbnameSelect.current()]
        rs=self.ms.ExecQuery('select logPath from task where id=?',(cur_taskid,))
        if not rs[0][0]:
            print(f'当前没有 {self.rwys.get(cur_taskid)} 的运行日志')
        else:
            logPath=rs[0][0]
            url=logPath.replace('D:/Web/Gtupdate',f'http://{UPDATE_URL}')
            print(url)
            while True:
                try:
                    res=requests.get(url)
                    bdpath=logPath.replace('D:/Web/Gtupdate/GTLOG/','')
                    with open(bdpath,'wb') as f:
                        f.write(res.content)
                    print(f'成功导出{self.rwys.get(cur_taskid)} 运行日志:《{bdpath}》')
                    messagebox.showinfo('提示',f'成功导出{self.rwys.get(cur_taskid)} 运行日志:《{bdpath}》')
                    break 
               
                except Exception as e:
                    print(e)
                    time.sleep(1)
    
        self.dcbtn.config(state=NORMAL)

class CloseTask(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.bmCount=IntVar()
        self.rbmCount=IntVar()
        self.createWidgets()

    def createWidgets(self):


        f0=Frame(self)
        f0.pack(fill=X)
        f00=Frame(f0)
        f00.pack(fill=X)

        Label(f00, text='选择任务:').pack(side=LEFT, padx=4, pady=2)
        self.dbnameSelect = ttk.Combobox(f00,state='readonly',width=20)
        self.dbnameSelect['value'] = list(TASK_DICT.keys())
        self.dbnameSelect.pack(side=LEFT, padx=5, pady=2)
        self.dbnameSelect.current(0)
    
        self.dcbtn=Button(f00,text='关闭所选任务',command=lambda:Thread(target=self.start_dc).start(),fg='#ffffff',bg='green')
        self.dcbtn.pack(side=LEFT, padx=2, pady=2)
    
    def start_dc(self):

        self.dcbtn.config(state=DISABLED)
        rw_name=self.dbnameSelect.get()
        cur_taskid=TASK_DICT.get(rw_name)
        aff=ms.ExecNoQuery('update task set state=-1 where id=? and state!=0',(cur_taskid,))
        if aff>0:
            print(f'成功关闭任务《{rw_name}》')
            messagebox.showinfo('提示',f'成功关闭任务《{rw_name}》')
        else:
            print(f'关闭任务《{rw_name}》失败')
            messagebox.showinfo('提示',f'关闭任务《{rw_name}》失败')

        self.dcbtn.config(state=NORMAL)

# import tkinter
# list_win=tkinter.Tk()
# list_win.wm_geometry("800x650")
# list_win.title('印尼虾皮群控操作')
# ShopeeQKFra(list_win).pack(fill=X,padx=3,pady=3)
# list_win.mainloop()